package com.imti.mapdemo;

import android.Manifest.permission;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListPopupWindow;
import androidx.appcompat.app.AppCompatActivity;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.ServiceSettings;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.Query;
import com.amap.api.services.poisearch.PoiSearch.SearchBound;
import com.tbruyelle.rxpermissions3.RxPermissions;
import io.reactivex.rxjava3.functions.Consumer;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
{

    private static final String TAG = MainActivity.class.getSimpleName();

    private MapView mapView;

    private AMap aMap;

    private String cityCode;

    private LatLonPoint searchPoint;

    private List<String> poiStrResultList;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //隐私政策合规
        ServiceSettings.updatePrivacyShow(this,true,true);
        ServiceSettings.updatePrivacyAgree(this,true);

        new RxPermissions(this)
            .request(permission.WRITE_EXTERNAL_STORAGE, permission.READ_EXTERNAL_STORAGE,
                permission.ACCESS_WIFI_STATE, permission.ACCESS_WIFI_STATE,
                permission.READ_PHONE_STATE, permission.ACCESS_COARSE_LOCATION)
            .subscribe(
                new Consumer<Boolean>()
                {
                    @Override
                    public void accept(Boolean granted) throws Throwable
                    {
                        if (granted)
                        {
                            initView(savedInstanceState);
                        }
                    }
                });
    }

    private void initView(Bundle savedInstanceState) throws Exception
    {
        mapView = findViewById(R.id.gd_map);
        mapView.onCreate(savedInstanceState);

        EditText searchEdit = findViewById(R.id.edit_map_poi);
        Button searchConfirBtn = findViewById(R.id.btn_map_poi_confirm);

        if (null == aMap)
        {
            aMap = mapView.getMap();
        }

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.interval(2000);
        myLocationStyle.showMyLocation(true);
        myLocationStyle.strokeColor(R.color.purple_500);
        myLocationStyle.radiusFillColor(Color.parseColor("#223700B3"));
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);

        aMap.setMyLocationStyle(myLocationStyle);
        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。

        AMapLocationClient client = new AMapLocationClient(this);
        AMapLocationClientOption option = new AMapLocationClientOption();

        option.setOnceLocation(false);
        option.setWifiScan(true);
        client.setLocationOption(option);

        client.setLocationListener(new AMapLocationListener()
        {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation)
            {
                if (null != aMapLocation)
                {
                    if (aMapLocation.getErrorCode() == 0)
                    {
                        Log.d(TAG,
                            "定位地点：" + aMapLocation.getProvince() + " " + aMapLocation.getCity()
                                + " " + aMapLocation.getDistrict() + " " + aMapLocation
                                                                               .getStreet());

                        cityCode = aMapLocation.getCityCode();
                        //定位点坐标
                        searchPoint = new LatLonPoint(aMapLocation.getLatitude(),
                            aMapLocation.getLongitude());

                        aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
                    }
                }
            }
        });

        client.startLocation();

        poiStrResultList = new ArrayList<>();
        ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1,
            poiStrResultList);

        //
        ListPopupWindow resultPopList = initSearchResultPopList(searchEdit, adapter);

        //搜索框设置点击事件
        searchConfirBtn.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Query query = new PoiSearch.Query(searchEdit.getText().toString(), "", cityCode);
                query.setPageNum(1);
                query.setPageSize(20);

                try
                {
                    PoiSearch search = new PoiSearch(MainActivity.this, query);

                    search.setBound(new SearchBound(searchPoint, 1000));
                    search.setOnPoiSearchListener(new OnPoiSearchListener()
                    {
                        @Override
                        public void onPoiSearched(PoiResult poiResult, int i)
                        {

                            if (poiResult.getPois() != null && !poiResult.getPois().isEmpty())
                            {
                                //2D地图绘制点
//                            aMap.clear();
//                            PoiOverlay poiOverlay = new PoiOverlay(aMap, poiResult.getPois());
//                            poiOverlay.removeFromMap();
//                            poiOverlay.addToMap();
//                            poiOverlay.zoomToSpan();

                                // 清理之前的图标
                                aMap.clear();
                                myPoiOverlay poiOverlay = new myPoiOverlay(aMap,
                                    poiResult.getPois());
                                poiOverlay.addToMap();
                                poiOverlay.zoomToSpan();

                                resultPopList.show();
                            }
                        }
                        @Override
                        public void onPoiItemSearched(PoiItem poiItem, int i)
                        {
                        }
                    });

                    search.searchPOIAsyn();


                } catch (AMapException e)
                {
                    e.printStackTrace();
                }
            }
        });

    }

    private ListPopupWindow initSearchResultPopList(View anchorView, ArrayAdapter adapter)
    {
        ListPopupWindow listPopup
            = new ListPopupWindow(MainActivity.this);

        listPopup.setAdapter(adapter);
        listPopup.setWidth(LayoutParams.MATCH_PARENT);
        listPopup.setHeight(LayoutParams.WRAP_CONTENT);
        listPopup.setAnchorView(anchorView);
        listPopup.setModal(true);

        return listPopup;
    }

    /**
     * 自定义PoiOverlay
     */

    private class myPoiOverlay
    {

        private AMap mamap;

        private List<PoiItem> mPois;

        private ArrayList<Marker> mPoiMarks = new ArrayList<Marker>();
        public myPoiOverlay(AMap amap, List<PoiItem> pois)
        {
            mamap = amap;
            mPois = pois;
        }

        /**
         * 添加Marker到地图中。
         *
         * @since V2.1.0
         */
        public void addToMap()
        {
            if (mPois != null)
            {
                int size = mPois.size();
                for (int i = 0; i < size; i++)
                {
                    Marker marker = mamap.addMarker(getMarkerOptions(i));
                    PoiItem item = mPois.get(i);
                    marker.setObject(item);
                    mPoiMarks.add(marker);
                }
            }
        }

        /**
         * 移动镜头到当前的视角。
         *
         * @since V2.1.0
         */
        public void zoomToSpan()
        {
            if (mPois != null && mPois.size() > 0)
            {
                if (mamap == null)
                {
                    return;
                }
                LatLngBounds bounds = getLatLngBounds();
                mamap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
            }
        }

        private LatLngBounds getLatLngBounds()
        {
            LatLngBounds.Builder b = LatLngBounds.builder();
            if (mPois != null)
            {
                int size = mPois.size();
                for (int i = 0; i < size; i++)
                {
                    b.include(new LatLng(mPois.get(i).getLatLonPoint().getLatitude(),
                        mPois.get(i).getLatLonPoint().getLongitude()));
                }
            }
            return b.build();
        }

        private MarkerOptions getMarkerOptions(int index)
        {
            poiStrResultList.add(getTitle(index));

            return new MarkerOptions()
                       .position(
                           new LatLng(mPois.get(index).getLatLonPoint()
                                          .getLatitude(), mPois.get(index)
                                                              .getLatLonPoint().getLongitude()))
                       .title(getTitle(index)).snippet(getSnippet(index));
        }

        protected String getTitle(int index)
        {
            return mPois.get(index).getTitle();
        }

        protected String getSnippet(int index)
        {
            return mPois.get(index).getSnippet();
        }

    }
}